package dbcon

import (
	"fmt"
	"net/http"
	"night-talk/model"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
)

//DBpostAaudio 上传一个音频文件
func DBpostAaudio(c *gin.Context, db *gorm.DB) {
	data, err := c.FormFile("data")
	poster := c.PostForm("poster")
	roomID := c.PostForm("roomid")
	roomIDint, err := strconv.ParseInt(roomID, 10, 64)

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"status":  "failure",
			"message": err.Error(),
		})
		return
	}

	var user model.User
	res := db.Where("name = ?", poster).Find(&user)
	if res.RowsAffected == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "用户不存在",
		})
		c.Abort()
		return
	}

	var room model.Room
	ress := db.Where("id = ?", roomIDint).Find(&room)
	if ress.RowsAffected == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "房间不存在",
		})
		c.Abort()
		return
	}

	fn := fmt.Sprintf("%s_%s", poster, data.Filename)
	a1 := model.Audio{Data: fn, Poster: poster, RoomID: uint(roomIDint)}
	db.Debug().Create(&a1)
	dst := fmt.Sprintf("./wavs/%s_%s", poster, data.Filename)
	fmt.Println("dst:", dst)
	// 上传文件到指定的目录
	err1 := c.SaveUploadedFile(data, dst)
	if err1 != nil {
		fmt.Println("文件上传失败")
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "文件上传失败",
		})
		c.Abort()
		return
	}
	//刷新当前的roomid信息
	saveFileNane := fmt.Sprintf("%s_%s", poster, data.Filename)
	if room.Audios == "" {
		fmt.Println("hello")
		room.Audios = saveFileNane
	} else {
		room.Audios += " " + saveFileNane
	}
	fmt.Println(room.Audios)
	db.Save(&room)

	//输出json结果给调用方
	c.JSON(http.StatusOK, a1)
}

// DBgetAWav 获取一张图片
func DBgetAWav(c *gin.Context, db *gorm.DB) {
	filename := c.Param("filename")
	c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; ")) //fmt.Sprintf("attachment; filename=%s", filename)对下载的文件重命名
	c.Writer.Header().Add("Content-Type", "audio/wav")
	dst := fmt.Sprintf("./wavs/%s", filename)
	c.File(dst)
}
